package com.ht.managermentserver.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ht.managermentserver.entity.SysUser;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * jwt 工具
 *
 * @author czy
 * @package com.ht.managermentserver.utils
 * @date 2020/6/3 13:32
 */
@Slf4j
public class JwtTokenUtil {

  private static final long EXPIRE_TIME = 12 * 60 * 60 * 1000;
  /** 密钥盐 */
  private static final String TOKEN_SECRET = "token123";

  public static String TOKEN_HEADER = "Authorization";

  /**
   * 签名生成
   *
   * @param user 用户
   * @return authorization
   */
  public static String createJwtToken(final SysUser user) {

    String token = null;
    try {
      final Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
      token =
          JWT.create()
              .withIssuer("auth0")
              .withClaim("userid", user.getId())
              .withExpiresAt(expiresAt)
              // 使用了HMAC256加密算法。
              .sign(Algorithm.HMAC256(TOKEN_SECRET));
    } catch (final Exception e) {
      e.printStackTrace();
    }
    return token;
  }

  /**
   * 签名验证
   *
   * @param token 加密 令牌
   * @return 验证是否成功
   */
  public static boolean verifyJwtToken(final String token) {

    try {
      final JWTVerifier verifier =
          JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
      final DecodedJWT jwt = verifier.verify(token);
      log.info("认证通过: ");
      log.info("issuer: " + jwt.getIssuer());
      log.info("userid: " + jwt.getClaim("userid").asLong());
      log.info("过期时间: " + jwt.getExpiresAt());
      return true;
    } catch (final Exception e) {
      log.info("认证失败");
      return false;
    }
  }

  public static Long getUserId(final String token) {

    final DecodedJWT jwt = JWT.decode(token);
    // DecodedJWT jwt = verifier.verify(token);
    return jwt.getClaim("userid").asLong();
  }
}
